package com.example.myapplication;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.myapplication.UserResponse;
import com.example.myapplication.UserRepository;

import java.util.List;

public class UserViewModel extends ViewModel {
    private final UserRepository userRepository;
    private final MutableLiveData<List<UserResponse.User>> userListLiveData = new MutableLiveData<>();
    private final MutableLiveData<Boolean> isLoadingLiveData = new MutableLiveData<>();
    private final MutableLiveData<String> errorMsgLiveData = new MutableLiveData<>();
    private final MutableLiveData<Boolean> isEmptyLiveData = new MutableLiveData<>();
    private final MutableLiveData<String> usernameLiveData = new MutableLiveData<>();
    private final MutableLiveData<String> interestLiveData = new MutableLiveData<>();

    public UserViewModel() {
        this.userRepository = new UserRepository();
    }

    public MutableLiveData<List<UserResponse.User>> getUserListLiveData() {
        return userListLiveData;
    }

    public MutableLiveData<Boolean> getIsLoadingLiveData() {
        return isLoadingLiveData;
    }

    public MutableLiveData<String> getErrorMsgLiveData() {
        return errorMsgLiveData;
    }

    public MutableLiveData<Boolean> getIsEmptyLiveData() {
        return isEmptyLiveData;
    }

    public LiveData<String> getUsername() {
        return usernameLiveData;
    }

    public LiveData<String> getCurrentInterest() {
        return interestLiveData;
    }

    public void updateInterest(String interest) {
        interestLiveData.setValue(interest);
    }

    public void fetchUserList() {
        isLoadingLiveData.setValue(true);
        errorMsgLiveData.setValue(null);
        isEmptyLiveData.setValue(false);

        userRepository.getUserList(new UserRepository.GetUserListCallback() {
            @Override
            public void onSuccess(UserResponse userResponse) {
                isLoadingLiveData.setValue(false);
                if (userResponse != null && userResponse.getData() != null && !userResponse.getData().isEmpty()) {
                    userListLiveData.setValue(userResponse.getData());
                } else {
                    isEmptyLiveData.setValue(true);
                    userListLiveData.setValue(null);
                }
            }

            @Override
            public void onFailure(String errorMsg) {
                isLoadingLiveData.setValue(false);
                errorMsgLiveData.setValue(errorMsg);
                userListLiveData.setValue(null);
            }
        });
    }

    public void updateUsername(String username) {
        usernameLiveData.setValue(username);
    }
}